<template>
  <a-table
    v-if="dataSource.length > 0"
    :dataSource="dataSource"
    :columns="columnsFilter"
    :pagination="query"
    @change="onChange"
    :loading="loading"
    :size="lineheight"
    :row-key="record => record.userId"
    :row-selection="rowSelectionActive ? rowSelection : null"
  >
    <template #bodyCell="{ column = {}, record }">
      <template v-if="column.key === 'operation'">
        <check-button :data="record" />
      </template>
      <template v-if="column.key === 'gmtCreate'">
        <span>
          {{
            record.gmtCreate
              ? dayjs.utc(record.gmtCreate).format('YYYY-MM-DD HH:mm:ss')
              : ''
          }}
        </span>
      </template>
      <template v-if="column.key === 'joinTime'">
        <span>
          {{
            record.joinTime
              ? dayjs.utc(record.joinTime).format('YYYY-MM-DD')
              : ''
          }}
        </span>
      </template>
      <template v-if="column.key === 'internshipEndDate'">
        <span>
          {{
            record.internshipEndDate
              ? dayjs.utc(record.internshipEndDate).format('YYYY-MM-DD')
              : '-'
          }}
        </span>
      </template>
      <template v-if="column.key === 'userStatus'">
        <div
          style="display: flex; flex-wrap: nowrap; align-items: center"
          v-if="record.userStatus === 'job'"
        >
          <span
            :style="{
              width: '6px',
              height: '6px',
              borderRadius: '100%',
              marginRight: '8px',
              backgroundColor: '#52c41a',
            }"
          ></span>
          <div>在职</div>
        </div>
        <div
          style="display: flex; flex-wrap: nowrap; align-items: center"
          v-else-if="record.userStatus === 'intern'"
        >
          <span
            :style="{
              width: '6px',
              height: '6px',
              borderRadius: '100%',
              marginRight: '8px',
              backgroundColor: '#0086ff',
            }"
          ></span>
          <div>实习</div>
        </div>
        <div
          style="display: flex; flex-wrap: nowrap; align-items: center"
          v-else
        >
          <span
            :style="{
              width: '6px',
              height: '6px',
              borderRadius: '100%',
              marginRight: '8px',
              backgroundColor: '#d3d3d3',
            }"
          ></span>
          <div>离职</div>
        </div>
      </template>
      <template v-if="column.key === 'isActivated'">
        <span>
          <a-tag :color="record.isActivated === 1 ? 'green' : 'default'">
            {{ record.isActivated === 1 ? '已发布' : '未发布' }}
          </a-tag>
        </span>
      </template>
      <template v-if="column.key === 'roleList'">
        <div class="role-table-cell" @click.stop>
          <a-space>
            <div
              style="
                width: 93px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              "
            >
              {{ record.roleList.length > 0 ? record.roleList.join(',') : '-' }}
            </div>
          </a-space>
          <a-space>
            <a-popover
              placement="bottom"
              trigger="click"
              overlayClassName="custom-popover"
              v-model:open="record.visible"
            >
              <template #content>
                <a-checkbox-group
                  v-model:value="record.roleList"
                  @change="handleRoleBind(record)"
                >
                  <div
                    v-for="option in options"
                    :key="option.value"
                    class="role-table-cell"
                  >
                    <a-space>
                      <div
                        style="
                          width: 93px;
                          overflow: hidden;
                          text-overflow: ellipsis;
                          white-space: nowrap;
                        "
                      >
                        {{ option.label }}
                      </div>
                    </a-space>
                    <a-space>
                      <a-checkbox :value="option.value"></a-checkbox>
                    </a-space>
                  </div>
                </a-checkbox-group>
              </template>
              <DownOutlined :style="{ fontSize: '16px', color: '#d3d3d3' }" />
            </a-popover>
          </a-space>
        </div>
      </template>
    </template>
  </a-table>
  <div
    v-else
    style="
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    "
  >
    <a-spin :spinning="loading">
      <a-empty
        :image="notData"
        :description="loading ? '加载中...' : '暂无数据'"
      />
    </a-spin>
  </div>
</template>
<script setup>
import { onMounted, computed, watch, ref } from 'vue'
import ATable from '@/components/table.vue'
import CheckButton from './table-content-view.vue'
import notData from '@/assets/images/not-data.png'
import { DownOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import {
  useColumns,
  useQuery,
  useDataSourceManager,
  useDataSource,
  useLineheight,
  useLoading,
  useRowSelection,
  useRowSelectionActive,
  useFiltersUser,
  useSortUser,
} from './provide-context.js'
import dayjs from 'dayjs'
import { getRoleNames, bindRoles } from '@/api/role.js'
/**
 * 外部参数
 */
let props = defineProps({
  currentTab: { type: String, required: true },
})
/**
 * 全局数据
 */
let columns = useColumns()
let dataSource = useDataSource()
let filtersUser = useFiltersUser()
let sortUser = useSortUser()
let query = useQuery()
let loading = useLoading()
let lineheight = useLineheight()
let { update } = useDataSourceManager()
let popVisible = ref(false)
/**
 * 表头
 */
let columnsFilter = computed(() => {
  // 给表格列添加过滤和排序
  columns.value.forEach(e => {
    if (e.key === 'joinTime') {
      e.sortOrder =
        sortUser?.value?.columnKey === 'joinTime' && sortUser?.value?.order
    } else if (e.key === 'gmtCreate') {
      e.sortOrder =
        sortUser?.value?.columnKey === 'gmtCreate' && sortUser?.value?.order
    } else if (e.key === 'internshipEndDate') {
      e.sortOrder =
        sortUser?.value?.columnKey === 'internshipEndDate' &&
        sortUser?.value?.order
    } else if (e.key === 'userStatus') {
      e.filteredValue = filtersUser?.value?.userStatus || null
    } else if (e.key === 'isPublished') {
      e.filteredValue = filtersUser?.value?.isPublished || null
    } else if (e.key === 'isActivated') {
      e.filteredValue = filtersUser?.value?.isActivated || null
    }
  })
  return columns?.value?.filter(({ checked }) => checked) || []
})

const options = ref([])
// 监听路由变化，当路由发生变化时再次调用 fetchData 函数
watch(
  () => props.currentTab,
  () => {
    getRoleNames().then(res => {
      options.value = res.data
    })
  },
  { immediate: true },
)
/**
 * table组件分页、排序、筛选变化事件
 */
function onChange({ current, pageSize }, filters, sorter, { action }) {
  query.value.current = current
  query.value.pageSize = pageSize
  if (action !== 'paginate') {
    query.value.current = 1
    query.value.pageSize = 10
  }
  filtersUser.value = filters
  sortUser.value = sorter
  update()
}
//初始化调用
onMounted(() => {
  query.value.current = 1
  query.value.pageSize = 10
  update()
})
/**
 * 复选框
 */
let rowSelection = useRowSelection()
let rowSelectionActive = useRowSelectionActive()

async function handleRoleBind(record) {
  popVisible.value = false
  if (record.isActivated === 1) {
    if (record.roleList.length <= 0) {
      await update()
      message.error('已发布用户，至少绑定一个角色')
      return
    }
    try {
      const params = [{ userId: record.userId, roleList: record.roleList }]
      await bindRoles(params)
      await update()
      record.visible = false
      message.success('角色绑定成功')
    } catch (e) {
      record.visible = false
      message.error('角色绑定失败')
    }
  }
}
</script>
<style lang="less" scoped>
.role-table-cell {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  margin-right: 16px;
}
:global(.ant-checkbox-group) {
  display: block;
}
.ant-popover :global(.ant-popover-arrow) {
  display: none !important;
}
:global(.custom-popover .ant-popover-inner-content) {
  max-height: 177px;
  overflow-y: auto;
  overflow-x: hidden;
}

:global(.custom-popover) {
  width: 160px;
}
.ant-popover :global(.ant-popover-inner) {
  padding: 5px 10px 5px 16px !important;
  margin-top: -10px !important;
}
</style>
